package com.zwy.springinner.handler;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.ParameterizedTypeImpl;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zwy.springinner.anotation.RequestJson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class RequestJsonHandler implements HandlerMethodArgumentResolver {

    ThreadLocal<JSONObject> paramObject = new ThreadLocal<>();

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(RequestJson.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        JSONObject jsonObject = getJsonObject();
        Object o = jsonObject.get(methodParameter.getParameterName());
        RequestJson parameterAnnotation = methodParameter.getParameterAnnotation(RequestJson.class);
        //判断是否允许为空
        String message = String.format("参数%s不能为空", methodParameter.getParameterName());
        Assert.isFalse(parameterAnnotation.required() && o == null, message);
        //如果为空设置默认值
        if (o == null) {
            return convertParameter(methodParameter, parameterAnnotation.defaultValue());
        }
        return convertParameter(methodParameter, o);
    }

    private Object convertParameter(MethodParameter methodParameter, Object o) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        if (methodParameter.getParameterType().getTypeName().equals(List.class.getTypeName()) ||
                methodParameter.getParameterType().getTypeName().equals(Set.class.getTypeName())) {
            Type actualTypeArgument = ((ParameterizedTypeImpl) methodParameter.getGenericParameterType()).getActualTypeArguments()[0];
            return JSONUtil.toList((JSONArray) o, Class.forName(actualTypeArgument.getTypeName()));
        } else {
            return convertParameter(methodParameter, String.valueOf(o));
        }
    }

    private Object convertParameter(MethodParameter methodParameter, String obj) throws InstantiationException, IllegalAccessException, InvocationTargetException {
        Constructor<?>[] constructors = methodParameter.getParameterType().getConstructors();
        for (Constructor<?> constructor : constructors) {
            if (constructor.getParameterCount() == 1 && constructor.getParameters()[0].getParameterizedType().getTypeName().equals("java.lang.String")) {
                return constructor.newInstance(obj);
            }
        }
        return null;
    }

    private JSONObject getJsonObject() throws IOException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String inputStr;
        while ((inputStr = streamReader.readLine()) != null) {
            responseStrBuilder.append(inputStr);
        }
        String jsonStr = responseStrBuilder.toString();
        //如果没有参数，表示不是第一次进入
        if (StrUtil.isEmpty(jsonStr)) {
            return paramObject.get();
        }
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        paramObject.set(jsonObject);
        return jsonObject;
    }
}
